package serverAndThreads;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;



public class chatThread extends Thread{
	
	ArrayList clientList;
	
	int group_id;
	
	public chatThread(int group_id){
		
		this.group_id = group_id;
		
		clientList = new ArrayList<Client>();
		
	}
	
	public void run(){
		
		try {
			ServerSocket serverSocket = new ServerSocket(group_id + 5000);
			
			while(true){
				Socket socket = serverSocket.accept();
				Client client = new Client(socket);
				System.out.println("A client connected");
				clientList.add(client);
				new Thread(client).start();
				
			}
			
			
			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
		}
	}
	class Client implements Runnable {
		private Socket messageSocket = null ;
		private Socket chatSocket = null ;
		private DataInputStream inputMessage = null;
		private DataOutputStream outputMessage = null; 
		private DataInputStream inputChat = null;
		private DataOutputStream outputChat = null; 
		private boolean bConnected = false ;
		
		public Client(Socket message){
			this.messageSocket = message;
			try {
				inputMessage = new DataInputStream(messageSocket.getInputStream());
				outputMessage = new DataOutputStream(messageSocket.getOutputStream());
				bConnected = true ;
			} catch (IOException e) {    
			}
		}	
		
		
		public void send(String str){
			try{
				outputMessage.writeUTF(str);
			}catch(IOException e){
				e.printStackTrace();
			}         
		}
		
		public void run() {
			try{
				while(bConnected){
					
					String message = inputMessage.readUTF();
					String date = inputMessage.readUTF();
					String username = inputMessage.readUTF();
					
					for(int i = 0; i<clientList.size(); i++){
						
						Client c = (Client)clientList.get(i);
						c.send(message);
						c.send(date);
						c.send(username);
					}       
				} 
				
				
			}catch(IOException e){
			}
		}
		
	}

}


